package com.token.utils;

import java.io.*;

/**
 * @auther: henriy
 * @Date: 2023/12/4
 */
public class FileUtils {

    public static void main(String[] args) {
        String property = System.getProperty("user.dir");
        System.out.println(property);
        String separator = File.separator;
        String resultPath = property + separator + "src" + separator + "main" + separator + "resources" + separator + "templates" + separator;
        System.out.println(resultPath);

        // 文件路径
        String filePath = resultPath + "readFile.txt";
        try {
            readFile(filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }

        String fileName = resultPath + "outputFile.txt";

        // 这是要写入文件的数据
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 1; i < 21; i++) {
            stringBuilder.append("这是第：")
                    .append(i)
                    .append("行！！！")
                    .append("\n");
        }

        String result = stringBuilder.toString();
        System.out.println(result);
        // 去掉最后一个换行符
        writeToFile(fileName, result.substring(0, result.length() - 1));
    }

    /**
     * 读取文件
     *
     * @param filePath
     * @throws IOException
     */
    public static void readFile(String filePath) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        String line;

        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }

        reader.close();
    }

    /**
     * 以覆盖的方式写入文件
     *
     * @param fileName
     * @param data
     */
    public static void writeToFile(String fileName, String data) {
        try {
            // 创建一个写入缓冲区
            BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
            // 将数据写入缓冲区
            writer.write(data);
            // 关闭缓冲区
            writer.close();
            System.out.println("数据已成功写入文件: " + fileName);
        } catch (IOException e) {
            System.out.println("写入文件时发生错误: " + e.getMessage());
        }
    }

}
